//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package 力扣.题库.滑动窗口.变长滑动窗口.越长约合法;

import java.util.HashMap;

public class demo_2962 {
    public demo_2962() {
    }

    public static void main(String[] args) {
        int[] nums = new int[]{28, 5, 58, 91, 24, 91, 53, 9, 48, 85, 16, 70, 91, 91, 47, 91, 61, 4, 54, 61, 49};
        System.out.println(countSubarrays(nums, 1));
    }

    public static long countSubarrays(int[] nums, int k) {
        HashMap<Integer, Integer> numsmap = new HashMap();
        int n = nums.length;
        int max = 0;

        for(int num : nums) {
            numsmap.put(num, (Integer)numsmap.getOrDefault(num, 0) + 1);
            max = Math.max(max, num);
        }

        int maxNum = (Integer)numsmap.get(max);
        if (maxNum < k) {
            return 0L;
        } else {
            int left = 0;
            long count = 0L;
            HashMap<Integer, Integer> kmap = new HashMap();
            System.out.println(max);
            kmap.put(max, 0);

            for(int num : nums) {
                kmap.put(num, (Integer)kmap.getOrDefault(num, 0) + 1);

                while((Integer)kmap.get(max) == k) {
                    int leftNum = nums[left];
                    kmap.put(leftNum, (Integer)kmap.get(leftNum) - 1);
                    ++left;
                }

                count += (long)left;
            }

            return count;
        }
    }

    public static long countSubarrays2(int[] nums, int k) {
        int mx = 0;

        for(int x : nums) {
            mx = Math.max(mx, x);
        }

        long ans = 0L;
        int cntMx = 0;
        int left = 0;

        for(int x : nums) {
            if (x == mx) {
                ++cntMx;
            }

            for(; cntMx == k; ++left) {
                if (nums[left] == mx) {
                    --cntMx;
                }
            }

            ans += (long)left;
        }

        return ans;
    }
}
